#计算(2+x1)/(1+x2)-3x1+4x3的最小值，其中x1,x2,x3范围在0.1到0.9之间
from scipy.optimize import minimize
import numpy as np

def fun(args):
    a,b,c,d=args
    v=lambda x:(a+x[0])/(b+x[1])-c*x[0]+d*x[2]
    return v

def con(args):
    '''设置约束条件'''
    #约束条件 分为eq和ineq
    #eq表示函数结果等于0;ineq表示表达式大于等于0
    x0min,x0max,x1min,x1max,x2min,x2max=args
    cons=({'type':'ineq','fun':lambda x:x[0]-x0min},
          {'type':'ineq','fun':lambda x:-x[0]+x0max},
          {'type':'ineq','fun':lambda x:x[1]-x1min},
          {'type':'ineq','fun':lambda x:-x[1]+x1max},
          {'type':'ineq','fun':lambda x:x[2]-x2min},
          {'type':'ineq','fun':lambda x:-x[2]+x2max},
          )
    return cons

if __name__=='__main__':
    #定义常量值
    args=(2,1,3,4) #a,b,c,d
    #设置参数范围/约束条件
    args1=(0.1,0.9,0.1,0.9,0.1,0.9)#x0min,x0max,x1min,x1max,x2min,x2max
    cons=con(args1)
    #设置初始猜测值
    x0=np.asarray((0.5,0.5,0.5))

    #求最小值
    res=minimize(fun(args),x0,method='SLSQP',constraints=cons)

    #输出结果
    print(res.fun)
    print(res.success)
    print(res.x)